/**********************************************
** @Des: This file ...
** @Author: haodaquan
** @Date:   2017-09-08 10:21:13
** @Last Modified by:   haodaquan
** @Last Modified time: 2017-09-09 18:04:41
***********************************************/
package controllers

import (
	"newAi/new_web/models"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/dcfn/req"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type HomeController struct {
	BaseController
}

func (self *HomeController) Index() {
	self.Data["pageTitle"] = "系统首页"
	//self.display()
	self.TplName = "dist/index.html"
}

func (self *HomeController) Start() {
	self.Data["pageTitle"] = "控制面板"

	self.display()
}
func (self *HomeController) AdminStart() {
	self.Data["pageTitle"] = "控制面板"
	a := []int{2, 3}
	b := []int{2, 3, 3}
	data := [][]int{a, b, b}
	self.Data["data"] = data

	//获取话术模板给页面
	filters := make([]interface{}, 0)
	if self.isOrg == true {
		filters = append(filters, "owner_id", self.userId)
	}
	result, _ := models.TplGetList(1, self.pageSize, "tpl", filters...)
	tpl := make([]map[string]string, len(result))
	for k, v := range result {
		row := make(map[string]string)
		row["id"] = strconv.FormatInt(v.Id, 10)
		row["tpl_name"] = v.Tpl_name
		tpl[k] = row
	}
	self.Data["tpl"] = tpl

	gw, err := models.GetGateWayNameByUserId(self.userId)
	if err != nil {
		fmt.Println(err)
		beego.Error(err)
	} else {
		self.Data["gateways"] = gw
	}

	self.display()
}

//获取 首页信息
func (self *HomeController) GetGatewayAndTpl() {

	var err error
	data := make(map [string] interface{})
	filters := make([]interface{}, 0)
	if self.isOrg == true {
		filters = append(filters, "owner_id", self.userId)
	}
	result, _ := models.TplGetList(1, self.pageSize, "tpl", filters...)
	tpl := make([]map[string]string, len(result))
	for k, v := range result {
		row := make(map[string]string)
		row["id"] = strconv.FormatInt(v.Id, 10)
		row["tpl_name"] = v.Tpl_name
		tpl[k] = row
	}

	gw, err := models.GetGateWayNameByUserId(self.userId)
	if err != nil {
		fmt.Println(err)
		beego.Error(err)
	} else {

	}
	data["tpl"] = tpl
	data["gateway"] = gw

	self.ajaxJson(data, MSG_OK)
}

var Token string

//拨打电话
func (self *HomeController) TestCall() {
	var Api = beego.AppConfig.String("api.url")
	fmt.Println("-----------test call--------------------")
	number := self.GetString("number")
	tpl_id, _ := self.GetInt64("tpl_id")
	gateway := self.GetString("gateway")
	uuid := self.GetUUId()
	tpl_global, err := models.GetTplMuteAndMisMatchingById(tpl_id)
	var external string
	if gateway == "-1" {

		external = "false"
	} else {
		external = "true"
	}

Start_call:
	//发起拨打请求给FsGui
	req.Debug = true
	headers := req.Header{
		"Content-Type":  "application/json",
		"Authorization": "Nway " + Token,
	}
	param := req.Param{
		"Job_uuid":                  uuid,
		"Callernum":                 number,
		"Calleenum":                 "999888",
		"A_gatewayname":             gateway,
		"A_external":                external,
		"Cdr_url":                   "http://127.0.0.1:8091/cdr",
		"Event_url":                 "http://127.0.0.1:8091/event",
		"Record_file":               uuid + "_" + number,
		"A_effective_caller_id_num": "",
	}
	r, err := req.Post(Api+"/api/originate_i", headers, req.BodyJSON(param))
	if err != nil {
	} else if strings.Contains(r.String(), "Not") {
		GetToken()
		goto Start_call
	} else if err == nil {
		run_time := new(models.RunTimeModel)
		run_time.Call_id = uuid
		run_time.Taskid = 6
		run_time.Call_phone = number
		run_time.Gateway_id = 2
		run_time.Call_state = 0
		run_time.Call_time = time.Now().Format("2006-01-02 15:04:05")
		run_time.Answer_time = time.Now().Format("2006-01-02 15:04:05")
		run_time.Talk_crycle = 0
		run_time.Tpl_id = tpl_id
		run_time.Display_number = ""
		run_time.Number_map_id = 3
		run_time.Mismatch_times = 3
		run_time.Mute_times = 3

		for _, v := range tpl_global {
			if v.Node == -2 && v.Node_type == 1 {
				run_time.Mute = v.Node_content
			} else if v.Node_type == 0 && v.Node == -2 {
				run_time.Mute = v.Audio_path
			}
			if v.Node == -3 && v.Node_type == 1 {
				run_time.Mismatching = v.Node_content
			} else if v.Node == -3 && v.Node_type == 0 {
				run_time.Mismatching = v.Audio_path
			}

		}
		if _, err := models.RunTimeAdd(run_time); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}

	}

	self.ajaxMsg(r.String(), MSG_OK)
}

//获取 token
func GetToken() {
	var Api = beego.AppConfig.String("api.url")
	client := &http.Client{}
	v := map[string]string{"username": "admin", "password": "admin"}
	data, _ := json.Marshal(v)
	req, err := http.NewRequest("POST", Api+"/api/login", bytes.NewBuffer(data))
	if err != nil {
		// handle error
		fmt.Println("err：", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("err :", err)
		return
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		fmt.Println("err :", err)
		return
	} else {
		//使用 json.Unmarshal(data []byte, v interface{})进行转换,返回 error 信息
		var mapResult map[string]string
		err = json.Unmarshal(body, &mapResult)
		if err != nil {
			fmt.Println("err :", err)
			return
		}
		Token = mapResult["token"]
		fmt.Println(Token)

	}
}

//获取 首页信息
func (self *HomeController) GetHomeInfo() {

	var err error
	runtime, _ := models.GetRunTimeInfo(self.userId) //当前并发
	flowConut, _ := models.GetFlowCount(self.userId) //电话数量 ，对话超过4伦的
	robot, _ := beego.AppConfig.Int("robot")         //机器人数量
	cdrConut, _ := models.GetCdrInfo(self.userId)    //呼叫数量
	if err != nil {
		beego.Error(err)
	}

	number := make(map[string]interface{})
	number["runTime"] = runtime
	number["robot"] = robot - runtime
	number["cdrConut"] = cdrConut
	if flowConut == 0 && cdrConut == 0 { //计算当前呼唤出数量，如果都是为0，不能0/0
		number["flowConut"] = 0
	} else {
		number["flowConut"] = float64(flowConut) / float64(cdrConut) * 100.00 //计算转换率
	}
	number["taskCount"], err = models.GetTaskCount(self.userId) //获取今日任务
	if err != nil {
		beego.Error(err)
	}
	number["numberCount"], err = models.GetNumberCounts(self.userId) //获取今日号码总量
	if err != nil {
		beego.Error(err)
	}
	durationModel:=models.DurationModel{}
	number["DoneNumber"],durationModel, err = models.GetDoneNumberCounts(self.userId) //获取今日呼叫总数
	if err != nil {
		beego.Error(err)
	}
	number["durationSum"]=durationModel.Duration
	number["adc"]=durationModel.Adc
	number["connectNumber"], err = models.GetConnectCounts(self.userId) //获取接通
	if err != nil {
		beego.Error(err)
	}
	number["unconnectNumber"], err = models.GetUnconnectCounts(self.userId) //获取今日完成号码
	if err != nil {
		beego.Error(err)
	}

	self.ajaxJson(number, MSG_OK)
}
